package com.example.demo.service.impl;

import com.example.demo.model.demoModel;
import com.example.demo.service.demoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
@Slf4j
public class demoServiceImpl implements demoService {

    private static ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(3);

    private static volatile AtomicBoolean atomicBoolean = new AtomicBoolean(false);


    private static volatile long demo1 = 0L;

    private static volatile long demo2 = 0L;

    private static volatile long demo3 = 0L;

    private static volatile long v1 = 1L;


    @Override
    public List<demoModel> getAllCnt() {
        log.info("start demo1:{},demo2:{},demo3:{}",demo1,demo2,demo3);
        if (!atomicBoolean.get()) {
            synchronized (this) {
                if (!atomicBoolean.get()) {
                    init();
                    atomicBoolean.set(true);
                }
            }
        }
        List<demoModel> resp = new LinkedList<>();
        demoModel demoModel = new demoModel(demo1);
        resp.add(demoModel);

        demoModel = new demoModel(demo2);
        resp.add(demoModel);

        demoModel = new demoModel(demo3);
        resp.add(demoModel);

        return resp;
    }

    @Override
    public String getClean() {
        log.info("start demo1:{},demo2:{},demo3:{}",demo1,demo2,demo3);
        atomicBoolean.set(false);
        demo1 = 0L;
        demo2 = 0L;
        demo3 = 0L;
        log.info("end demo1:{},demo2:{},demo3:{}",demo1,demo2,demo3);
        return "success";
    }

    public static void init() {
        threadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                demo1 += v1;
                if (demo1 > 10L) demo1 = 0L;
            }
        }, 0, 1000, TimeUnit.MILLISECONDS);

        threadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                demo2 += v1;
                if (demo2 > 10L) demo2 = 0L;
            }
        }, 0, 2000, TimeUnit.MILLISECONDS);

        threadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                demo3 += v1;
                if (demo3 > 10L) demo3 = 0L;
            }
        }, 0, 3000, TimeUnit.MILLISECONDS);
    }


}
